from flask import Blueprint,render_template,jsonify,request
from models import BookModel,UserModel,BookInfoModel,CommentModel
from exts import db
from collections import Counter

bp = Blueprint("index", __name__, url_prefix="/")

# 跳转到首页
@bp.route("/index")
def index():
    return render_template("index.html")

# 文学类图书页面
@bp.route("/index/wenxue")
def wenxue():
    return render_template("categoryDetaile/wenxue.html")

# 科幻类图书页面
@bp.route("/index/kehuan")
def kehuan():
    return render_template("categoryDetaile/kehuan.html")

# 历史类图书页面
@bp.route("/index/lishi")
def lishi():
    return render_template("categoryDetaile/lishi.html")

# 专业书籍页面
@bp.route("/index/zhuanye")
def zhuanye():
    return render_template("categoryDetaile/zhuanye.html")

# 根据图书编号获取图书详细信息
@bp.route("/index/detail/<id>")
def detail(id):
    print("id:"+id)
    # 查询书籍详情信息
    bookinfo=db.session.query(BookInfoModel.bookid,BookInfoModel.bookauthor,BookInfoModel.bookdinfo,BookInfoModel.bookprice).filter_by(bookid=id).first()
    book=db.session.query(BookModel.bookname,BookModel.booksort).filter_by(bookid=id).first()
    content={'bookid':bookinfo[0],'bookauthor':bookinfo[1],'bookdinfo':bookinfo[2],'bookprice':bookinfo[3],'bookname':book[0],'sort':book[1],'src':book[0]+".png"}
    print(content)
    # 查询评论信息
    comments=CommentModel.query.filter_by(bookid=id).order_by(CommentModel.commentDate.desc()).all()
    data={}
    allcomment=[]
    star=[]
    # 显示评论
    for comment in comments:
        # 处理标签
        a=comment.content
        s=a.split('-')[1]
        lst = [x.strip('#') for x in s.split('#') if x]
        # 处理时间
        dt=comment.commentDate
        formatted_date = dt.strftime('%Y-%m-%d %H:%M:%S')
        data={'commentId':comment.commentId,'studentID':comment.studentID,'bookid':comment.bookid,'commentDate':formatted_date,'star':comment.star,
              'say':a.split('-')[0],'tags':lst,'name':selectById(comment.studentID)}
        allcomment.append(data)
        star.append((int)(comment.star))
    print(allcomment)
    print(star)
    # 统计每个星人数
    count = Counter(star)
    counts=[count[1],count[2],count[3],count[4],count[5]]
    print(counts)
    # 统计每个星百分比
    if len(star)==0:
        countpercent=["0%","0%","0%","0%","0%"]
    else:
        countpercent=["{:.0%}".format(count[1]/len(star)),"{:.0%}".format(count[2]/len(star)),"{:.0%}".format(count[3]/len(star)),"{:.0%}".format(count[4]/len(star)),"{:.0%}".format(count[5]/len(star)),]
    print(countpercent)
    # 总共人数
    if len(star)==0:
        all={'people':0,'avg':0}
    else:
        all={'people':len(star),'avg':sum(star)//len(star)}
    # 跳转到detail.html页面并传递多个参数用于渲染
    return render_template("categoryDetaile/detail.html",book=content,comments=allcomment,counts=counts,countpercent=countpercent,all=all)

# 根据用户id查找姓名
def selectById(id):
    user=UserModel.query.filter_by(userid=id).first()
    return user.username

# 分页获取图书
@bp.route("/book/list")
def book_list():
    # 前端传递参数第几页、每页多少、类型
    pageNum=request.args.get("pageNum",default=1)
    pageSize=request.args.get("pageSize",default=10)
    bookSort=request.args.get("bookSort",default="文学")
    booklists={}
    booklist=[]
    content={}
    books=db.session.query(BookModel.bookid,BookModel.bookname).filter_by(booksort=bookSort)
    count=db.session.query(BookModel).filter_by(booksort=bookSort).count()
    if count%pageSize==0:
        sum=count/pageSize
    else:
        sum=count/pageSize+1
    print(count/pageSize)
    # 分页查询
    page_objs = books.paginate(
        page=int(pageNum),
        per_page=int(pageSize),
        error_out=False,
        max_per_page=50,
    ).items
    print(count)
    print(page_objs)
    for result in page_objs:
        content={'bookid':result[0],'bookname':result[1]}
        booklist.append(content)
        content={}
    booklists={'list':booklist,'page':(int)(sum)}
    print(booklists)
    return jsonify(booklists)